import { useState, useCallback } from 'react'
import type { FormInstance } from 'antd'

interface UseModalProps<T, K = T> {
  form: FormInstance<T>
  onSuccess?: (values: T) => void
  editingItem?: K | null
}

/**
 * 通用的模态框控制 Hook
 * @param form - antd Form 实例
 * @param onSuccess - 成功回调
 */
export function useModal<T, K = T>({ form, onSuccess }: UseModalProps<T, K>) {
  const [visible, setVisible] = useState(false)
  const [loading, setLoading] = useState(false)
  const [editingItem, setEditingItem] = useState<K | null>(null)

  const showModal = useCallback((record?: K) => {
    if (record) {
      setEditingItem(record)
      form.setFieldsValue(record as any)
    } else {
      form.resetFields()
    }
    setVisible(true)
  }, [form])

  const hideModal = useCallback(() => {
    setVisible(false)
    setEditingItem(null)
    form.resetFields()
  }, [form])

  const handleSubmit = useCallback(async () => {
    try {
      setLoading(true)
      const values = await form.validateFields() as T
      onSuccess?.(values)
      setVisible(false)
    } catch (error) {
      console.error('Validate Failed:', error)
    } finally {
      setLoading(false)
    }
  }, [form, onSuccess])

  return {
    visible,
    loading,
    editingItem,
    showModal,
    hideModal,
    handleSubmit
  }
} 